package com.yupi.yupicturebackend.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qcloud.cos.model.ciModel.auditing.ImageAuditingResponse;
import com.qcloud.cos.model.ciModel.auditing.TextAuditingResponse;
import com.yupi.yupicturebackend.api.aliyunai.AliYunAiApi;
import com.yupi.yupicturebackend.api.aliyunai.model.outPainting.CreateOutPaintingTaskRequest;
import com.yupi.yupicturebackend.api.aliyunai.model.outPainting.CreateOutPaintingTaskResponse;
import com.yupi.yupicturebackend.api.aliyunai.model.test2Image.CreateText2ImageRequest;
import com.yupi.yupicturebackend.api.aliyunai.model.test2Image.CreateText2ImageResponse;
import com.yupi.yupicturebackend.api.baidu.imageUnderstand.ImageUnderstandingFacade;
import com.yupi.yupicturebackend.api.deepseek.DeepseekApi;
import com.yupi.yupicturebackend.async.AsyncPictureService;
import com.yupi.yupicturebackend.constant.ReviewPictureConstant;
import com.yupi.yupicturebackend.exception.BusinessException;
import com.yupi.yupicturebackend.exception.ErrorCode;
import com.yupi.yupicturebackend.exception.ThrowUtils;
import com.yupi.yupicturebackend.manager.CosManager;
import com.yupi.yupicturebackend.manager.auth.SpaceUserAuthManager;
import com.yupi.yupicturebackend.manager.auth.StpKit;
import com.yupi.yupicturebackend.manager.auth.model.SpaceUserPermissionConstant;
import com.yupi.yupicturebackend.manager.upload.FilePictureUpload;
import com.yupi.yupicturebackend.manager.upload.PictureUploadTemplate;
import com.yupi.yupicturebackend.manager.upload.UrlPictureUpload;
import com.yupi.yupicturebackend.mapper.UserPictureViewMapper;
import com.yupi.yupicturebackend.model.dto.file.UploadPictureResult;
import com.yupi.yupicturebackend.model.dto.picture.*;
import com.yupi.yupicturebackend.model.entity.Picture;
import com.yupi.yupicturebackend.model.entity.Space;
import com.yupi.yupicturebackend.model.entity.User;
import com.yupi.yupicturebackend.model.entity.UserPictureView;
import com.yupi.yupicturebackend.model.enums.PictureReviewStatusEnum;
import com.yupi.yupicturebackend.model.enums.ReviewPictureEnum;
import com.yupi.yupicturebackend.model.vo.PictureVO;
import com.yupi.yupicturebackend.model.vo.UserVO;
import com.yupi.yupicturebackend.service.PictureService;
import com.yupi.yupicturebackend.mapper.PictureMapper;
import com.yupi.yupicturebackend.service.SpaceService;
import com.yupi.yupicturebackend.service.UserService;
import com.yupi.yupicturebackend.utils.ColorSimilarUtils;
import lombok.extern.slf4j.Slf4j;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.annotation.Id;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.support.TransactionTemplate;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.awt.*;
import java.io.IOException;
import java.util.*;
import java.util.List;
import java.util.stream.Collectors;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;

import static com.yupi.yupicturebackend.constant.RedisConstants.PICTURE_LIKED_KEY;

/**
 * @author Administrator
 * @description 针对表【picture(图片)】的数据库操作Service实现
 * @createDate 2025-03-06 15:48:22
 */
@Service
@Slf4j
public class PictureServiceImpl extends ServiceImpl<PictureMapper, Picture>
        implements PictureService {

    //    @Resource
//    private FileManager fileManager;
    @Resource
    private UserService userService;

    @Resource
    private UrlPictureUpload urlPictureUpload;
    @Resource
    private FilePictureUpload filePictureUpload;
    @Resource
    private CosManager cosManager;
    @Resource
    private SpaceService spaceService;
    @Resource
    private TransactionTemplate transactionTemplate;
    @Resource
    private AliYunAiApi aliYunAiApi;
    @Resource
    private SpaceUserAuthManager spaceUserAuthManager;
    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Resource
    private UserPictureViewMapper userPictureViewMapper;

    private final BlockingQueue<String> taskQueue = new LinkedBlockingQueue<>();
    @Resource
    private DeepseekApi deepseekApi;
    @Resource
    private PictureMapper pictureMapper;


    @PostConstruct
    public void init() {
        // 启动一个线程来处理任务队列
        new Thread(() -> {
            while (true) {
                try {
                    String taskId = taskQueue.take();
                    checkTaskStatus(taskId);
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                    log.error("Task processing thread interrupted", e);
                }
            }
        }).start();
    }

    @Override
    public PictureVO uploadPicture(Object inputSource, PictureUploadRequest pictureUploadRequest, User loginUser) {
        ThrowUtils.throwIf(loginUser == null, ErrorCode.NO_AUTH_ERROR);
        // 校验空间是否存在
        Long spaceId = pictureUploadRequest.getSpaceId();
        if (spaceId != null) {
            Space space = spaceService.getById(spaceId);
            ThrowUtils.throwIf(space == null, ErrorCode.NOT_FOUND_ERROR, "空间不存在");
            // 必须空间创建人（管理员）才能上传
//            if (!loginUser.getId().equals(space.getUserId())) {
//                throw new BusinessException(ErrorCode.NO_AUTH_ERROR, "没有空间权限");
//            }

            // 校验额度
            if (space.getTotalCount() >= space.getMaxCount()) {
                throw new BusinessException(ErrorCode.OPERATION_ERROR, "空间条数不足");
            }
            if (space.getTotalSize() >= space.getMaxSize()) {
                throw new BusinessException(ErrorCode.OPERATION_ERROR, "空间大小不足");
            }

        }

        // 用于判断是新增还是更新图片
        Long pictureId = null;
        if (pictureUploadRequest != null) {
            pictureId = pictureUploadRequest.getId();
        }
        // 如果是更新图片，需要校验图片是否存在
        /**
         * ::用法
         * 等效于 lambda 表达式：picture -> picture.getId()
         * 即 (picture) -> { return picture.getId(); }
         * 再具体
         * new Function<Picture, Long>() {
         *     @Override
         *     public Long apply(Picture picture) {
         *         return picture.getId();
         *     }
         * }
         *
         * ::核心就是通过一个类名再来一个该类的实例方法（这下面有返回值） 就可以获取到某个类的属性  这里是getId()方法
         *
         * 为什么这里必须用lamba 表达式，因为 lambdaQuery().eq 方法需要一个函数式接口  直接使用字符串是不行的
         *
         * 此外 这里的lambdaQuery().eq 方法里传Picture::getId这种参数，可以避免硬编码问题 增强可读性
         * 让开发者知道是哪个类的id
         *
         */
        Picture oldPicture = null;
        if (pictureId != null) {
            oldPicture = this.getById(pictureId);
            ThrowUtils.throwIf(oldPicture == null, ErrorCode.NOT_FOUND_ERROR, "图片不存在");
            /**
             * 这里影响到了 团队空间的图片编辑权限  对于团队里其他用户 无法在编辑图片后 进行图片上传的操作
             */
//            if (!oldPicture.getUserId().equals(loginUser.getId()) && !userService.isAdmin(loginUser)) {
//                throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
//            }

            // 校验空间是否一致
            // 没传 spaceId，则复用原有图片的 spaceId  场景往公共图库上传
            if (spaceId == null) {
                if (oldPicture.getSpaceId() != null) {
                    spaceId = oldPicture.getSpaceId();
                }
            } else {
                // 传了 spaceId，必须和原有图片一致
                if (ObjUtil.notEqual(spaceId, oldPicture.getSpaceId())) {
                    throw new BusinessException(ErrorCode.PARAMS_ERROR, "空间 id 不一致");
                }
            }

//            boolean exists = this.lambdaQuery()
//                    .eq(Picture::getId, pictureId)
//                    .exists();
//            boolean exists = this.query()
//                    .eq("id", pictureId)
//                    .exists();
        }
        // 上传图片，得到信息

        // 按照用户 id 划分目录 => 按照空间划分目录
        String uploadPathPrefix;
        if (spaceId == null) {
            // 按照用户 id 划分目录
            uploadPathPrefix = String.format("public/%s", loginUser.getId());
        } else {
            uploadPathPrefix = String.format("space/%s", spaceId);
        }

//        UploadPictureResult uploadPictureResult = fileManager.uploadPicture(multipartFile, uploadPathPrefix);
        PictureUploadTemplate pictureUploadTemplate = filePictureUpload;
        if (inputSource instanceof String) {
            pictureUploadTemplate = urlPictureUpload;
        }
        UploadPictureResult uploadPictureResult = pictureUploadTemplate.uploadPicture(inputSource, uploadPathPrefix);

        /**
         * 将Picture对象构建代码抽取出来，避免代码冗余
         */
        Picture picture = getPicture(loginUser, uploadPictureResult, pictureUploadRequest, pictureId, spaceId);

        // 开启事务
        Long finalSpaceId = spaceId;
        Long finalPictureId = pictureId;
        Picture finalOldPicture = oldPicture;

        // 执行事务并获取带ID的实体
        Picture savedPicture = transactionTemplate.execute(status -> {
            boolean result = this.saveOrUpdate(picture);
            ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR, "图片上传失败");
            /**
             * 必须是有指定的私有空间id才行
             * 更新上传图片
             * 1.对象存储上的被替换的旧照片要删除
             * 2.space的当前size要 - 旧照片大小 + 新照片大小
             * 3.space的当前count不变
             */
            if (finalSpaceId != null && finalPictureId != null) {
                boolean update = spaceService.lambdaUpdate()
                        .eq(Space::getId, finalSpaceId)
                        // space的当前size要 - 旧照片大小 + 新照片大小
                        .setSql("totalSize = totalSize - " + finalOldPicture.getPicSize() + " + " + picture.getPicSize())
//                        .setSql("totalCount = totalCount + 1")  space的当前count不变
                        .update();
                ThrowUtils.throwIf(!update, ErrorCode.OPERATION_ERROR, "额度更新失败");
                // 对象存储上的被替换的旧照片要删除
                this.clearPictureFile(finalOldPicture);
                /**
                 * 上传新的图片
                 * 1.space的当前size要 + 新照片大小
                 * 2.space的当前count要+1
                 */
            } else if (finalSpaceId != null && finalPictureId == null) {
                boolean update = spaceService.lambdaUpdate()
                        .eq(Space::getId, finalSpaceId)
                        .setSql("totalSize = totalSize + " + picture.getPicSize())
                        .setSql("totalCount = totalCount + 1")
                        .update();
                ThrowUtils.throwIf(!update, ErrorCode.OPERATION_ERROR, "额度新增失败");
            }

            return picture;
        });

        PictureVO pictureVO = PictureVO.objToVo(picture);

//        异步执行 图像理解的描述元素到数据库
        // 校验 savedPicture 是否为 null   这个判断多余了  为空也走不到这里
//        if (savedPicture == null) {
//            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR, "图片不存在");
//        }
//        this.savePictureElements(uploadPictureResult.getUrl(), "这张图片里有什么？", savedPicture.getId());
// 最后触发异步（不等待）
//        try {
//            this.savePictureElements(
//                    uploadPictureResult.getUrl(),
//                    "这张图片里有什么？",
//                    savedPicture.getId()
//            );
//        } catch (Exception e) {
//            log.error("异步任务提交失败（不影响主流程）", e);
//        }

        // 之前异步处理 不生效 这里 创建专门的异步服务 去调用
//        只对公共图库上传的图片才异步处理
        if (spaceId == null) {
            asyncPictureService.asyncProcess(
                    uploadPictureResult.getUrl(),
                    "这张图片里有什么？",
                    savedPicture.getId()
            );
        }

        return pictureVO;
    }

    @Autowired
    private AsyncPictureService asyncPictureService; // 关键：跨Bean调用

    private Picture getPicture(User loginUser, UploadPictureResult uploadPictureResult, PictureUploadRequest pictureUploadRequest, Long pictureId, Long spaceId) {
        // 构造要入库的图片信息
        Picture picture = new Picture();
        picture.setSpaceId(spaceId);
        picture.setUrl(uploadPictureResult.getUrl());
        picture.setThumbnailUrl(uploadPictureResult.getThumbnailUrl());
//        数据万象解析出来的图片名字  默认的
        String picName = uploadPictureResult.getPicName();
//        外层传递的图片名称 针对批量爬取图片后上传图片时使用
        if (pictureUploadRequest != null && StrUtil.isNotBlank(pictureUploadRequest.getPicName())) {
            picName = pictureUploadRequest.getPicName();
        }
        picture.setName(picName);
        picture.setPicSize(uploadPictureResult.getPicSize());
        picture.setPicWidth(uploadPictureResult.getPicWidth());
        picture.setPicHeight(uploadPictureResult.getPicHeight());
        picture.setPicScale(uploadPictureResult.getPicScale());
        picture.setPicFormat(uploadPictureResult.getPicFormat());
        picture.setUserId(loginUser.getId());
        picture.setPicColor(uploadPictureResult.getPicColor());
        /**
         * 因为有多个地方会用到 填充审核状态为待审核的情况 所以应该专门封装一个方法 而不是写死代码
         * 比如 编辑图片信息  更新图片  上传图片 三个地方用到了
         */
//        picture.setReviewStatus(PictureReviewStatusEnum.REVIEWING.getValue());
        this.fillReviewParams(picture, loginUser);
        // 如果 pictureId 不为空，表示更新，否则是新增
        if (pictureId != null) {
            // 如果是更新，需要补充 id 和编辑时间
            picture.setId(pictureId);
            picture.setEditTime(new Date());
        }
        return picture;
    }


    @Override
    public QueryWrapper<Picture> getQueryWrapper(PictureQueryRequest pictureQueryRequest) {
        QueryWrapper<Picture> queryWrapper = new QueryWrapper<>();
        if (pictureQueryRequest == null) {
            return queryWrapper;
        }
        // 从对象中取值
        Long id = pictureQueryRequest.getId();
        String name = pictureQueryRequest.getName();
        String introduction = pictureQueryRequest.getIntroduction();
        String category = pictureQueryRequest.getCategory();
        List<String> tags = pictureQueryRequest.getTags();
        Long picSize = pictureQueryRequest.getPicSize();
        Integer picWidth = pictureQueryRequest.getPicWidth();
        Integer picHeight = pictureQueryRequest.getPicHeight();
        Double picScale = pictureQueryRequest.getPicScale();
        String picFormat = pictureQueryRequest.getPicFormat();
        String searchText = pictureQueryRequest.getSearchText();
        Long userId = pictureQueryRequest.getUserId();
        String sortField = pictureQueryRequest.getSortField();
        String sortOrder = pictureQueryRequest.getSortOrder();
        // 补充 审核参数
        Long reviewerId = pictureQueryRequest.getReviewerId();
        Integer reviewStatus = pictureQueryRequest.getReviewStatus();
        String reviewMessage = pictureQueryRequest.getReviewMessage();
        Long spaceId = pictureQueryRequest.getSpaceId();
        boolean nullSpaceId = pictureQueryRequest.isNullSpaceId();
        Date startEditTime = pictureQueryRequest.getStartEditTime();
        Date endEditTime = pictureQueryRequest.getEndEditTime();
        List<String> elements = pictureQueryRequest.getElements();
        // 从多字段中搜索
        if (StrUtil.isNotBlank(searchText)) {
            // 需要拼接查询条件
            /**
             * 拼接查询条件  因为下面的都是用and连接的  所以这里的or要包裹起来
             * and  (name like '%xxx%' or introduction like '%xxx%')
             */
            queryWrapper.and(qw -> qw.like("name", searchText)
                    .or()
                    .like("introduction", searchText)
            );
        }
        /**
         * 每个queryWrapper与queryWrapper构造的查询条件 都是 and 连接的
         */
        queryWrapper.eq(ObjUtil.isNotEmpty(id), "id", id);
        queryWrapper.eq(ObjUtil.isNotEmpty(userId), "userId", userId);
        queryWrapper.like(StrUtil.isNotBlank(name), "name", name);
        queryWrapper.like(StrUtil.isNotBlank(introduction), "introduction", introduction);
        queryWrapper.like(StrUtil.isNotBlank(picFormat), "picFormat", picFormat);
        queryWrapper.eq(StrUtil.isNotBlank(category), "category", category);
        queryWrapper.eq(ObjUtil.isNotEmpty(picWidth), "picWidth", picWidth);
        queryWrapper.eq(ObjUtil.isNotEmpty(picHeight), "picHeight", picHeight);
        queryWrapper.eq(ObjUtil.isNotEmpty(picSize), "picSize", picSize);
        queryWrapper.eq(ObjUtil.isNotEmpty(picScale), "picScale", picScale);
        queryWrapper.eq(ObjUtil.isNotEmpty(reviewStatus), "reviewStatus", reviewStatus);
        queryWrapper.like(StrUtil.isNotBlank(reviewMessage), "reviewMessage", reviewMessage);
        queryWrapper.eq(ObjUtil.isNotEmpty(reviewerId), "reviewerId", reviewerId);
        queryWrapper.eq(ObjUtil.isNotEmpty(spaceId), "spaceId", spaceId);
        queryWrapper.isNull(nullSpaceId, "spaceId");  //ture就是null  false就不用这个条件
        queryWrapper.ge(ObjUtil.isNotEmpty(startEditTime), "editTime", startEditTime);
        queryWrapper.lt(ObjUtil.isNotEmpty(endEditTime), "editTime", endEditTime);

//        sgy的优化
//        queryWrapper.isNull(ObjUtil.isEmpty(spaceId), "spaceId");

        // JSON 数组查询
        /**
         下面这个是and的方式 例如： tags LIKE '%"风景"%' and tags LIKE '%"日落"%'
         但是 要包裹起来 变成and (tags LIKE '%"风景"%' and tags LIKE '%"日落"%')
         *
         */
        if (CollUtil.isNotEmpty(tags)) {
            for (String tag : tags) {
                queryWrapper.like("tags", "\"" + tag + "\"");
            }
        }

        // 通过元素去查询相关图片
        if (CollUtil.isNotEmpty(elements)) {
            queryWrapper.and(qw -> {
                for (String element : elements) {
                    qw.or().like("elements", element);
                }
            });
        }

        // 排序
        queryWrapper.orderBy(StrUtil.isNotEmpty(sortField), sortOrder.equals("ascend"), sortField);
        return queryWrapper;
    }


    @Override
    public PictureVO getPictureVO(Picture picture, HttpServletRequest request) {
        // 对象转封装类
        PictureVO pictureVO = PictureVO.objToVo(picture);
        // 关联查询用户信息
        Long userId = picture.getUserId();
        if (userId != null && userId > 0) {
            User user = userService.getById(userId);
            UserVO userVO = userService.getUserVO(user);
            pictureVO.setUser(userVO);
        }
        return pictureVO;
    }


    /**
     * 分页获取图片封装
     */
    @Override
    public Page<PictureVO> getPictureVOPage(Page<Picture> picturePage, HttpServletRequest request) {
        List<Picture> pictureList = picturePage.getRecords();
        Page<PictureVO> pictureVOPage = new Page<>(picturePage.getCurrent(), picturePage.getSize(), picturePage.getTotal());
        if (CollUtil.isEmpty(pictureList)) {
            return pictureVOPage;
        }
        // 对象列表 => 封装对象列表

        /**
         * map方法的基本用法是在Stream对象中的每个元素上应用一个函数，然后将函数的结果收集到一个新的Stream对象中
         * 这里是直接把新的Stream对象收集到了指定List集合里了，所以最后返回的还是List
         */

        List<PictureVO> pictureVOList = pictureList.stream().map(PictureVO::objToVo).collect(Collectors.toList());
        // 1. 关联查询用户信息
        Set<Long> userIdSet = pictureList.stream().map(Picture::getUserId).collect(Collectors.toSet());
        /**
         * userService.listByIds(userIdSet) 是通过多个id批量获取用户详细信息变成 List<User>
         * .stream() 是将集合转换为流，.collect(Collectors.groupingBy(User::getId)) 是将流中的元素根据id分组，返回一个Map
         * 现在Map里每个userId 对应一个用户信息，但这个用户信息是List<User>，而不是User
         */
        Map<Long, List<User>> userIdUserListMap = userService.listByIds(userIdSet).stream()
                .collect(Collectors.groupingBy(User::getId));
        // 2. 填充信息
        pictureVOList.forEach(pictureVO -> {
            Long userId = pictureVO.getUserId();
            User user = null;
            if (userIdUserListMap.containsKey(userId)) {
//                List<User> users = userIdUserListMap.get(userId);
                user = userIdUserListMap.get(userId).get(0);
            }
            pictureVO.setUser(userService.getUserVO(user));
        });
        pictureVOPage.setRecords(pictureVOList);
        return pictureVOPage;
    }

    @Override
    public void validPicture(Picture picture) {
        ThrowUtils.throwIf(picture == null, ErrorCode.PARAMS_ERROR);
        // 从对象中取值
        Long id = picture.getId();
        String url = picture.getUrl();
        String introduction = picture.getIntroduction();
        // 修改数据时，id 不能为空，有参数则校验
        ThrowUtils.throwIf(ObjUtil.isNull(id), ErrorCode.PARAMS_ERROR, "id 不能为空");
        if (StrUtil.isNotBlank(url)) {
            ThrowUtils.throwIf(url.length() > 1024, ErrorCode.PARAMS_ERROR, "url 过长");
        }
        if (StrUtil.isNotBlank(introduction)) {
            ThrowUtils.throwIf(introduction.length() > 800, ErrorCode.PARAMS_ERROR, "简介过长");
        }
    }

    @Override
    public void doPictureReview(PictureReviewRequest pictureReviewRequest, User loginUser) {
        Long id = pictureReviewRequest.getId();
        Integer reviewStatus = pictureReviewRequest.getReviewStatus();
        PictureReviewStatusEnum reviewStatusEnum = PictureReviewStatusEnum.getEnumByValue(reviewStatus);
        /**
         * 这个是管理员审核过图片  之后又要做重新审核来修改审核状态的 所以 不能修改状态为待审核的这种情况
         */
        if (id == null || reviewStatusEnum == null || PictureReviewStatusEnum.REVIEWING.equals(reviewStatusEnum)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        // 判断是否存在
        Picture oldPicture = this.getById(id);
        ThrowUtils.throwIf(oldPicture == null, ErrorCode.NOT_FOUND_ERROR);
        // 已是该状态
        /**
         * 这个不会出现吧？走到这 就说明肯定是待审核状态呀
         * 这个是审核之前已经审核过的图片  重新审核了
         * 比如 这次第二次要把之前的通过状态改为 拒绝  如果参数里传过来的还是通过状态 就属于修改为同一个状态了
         */
        if (oldPicture.getReviewStatus().equals(reviewStatus)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "请勿重复审核");
        }
        // 更新审核状态
        Picture updatePicture = new Picture();
        BeanUtils.copyProperties(pictureReviewRequest, updatePicture);
        updatePicture.setReviewerId(loginUser.getId());
        updatePicture.setReviewTime(new Date());
        boolean result = this.updateById(updatePicture);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
    }

    @Override
    public boolean doAIPictureReview(List<PictureAIReviewRequest> pictureAIReviewRequests) {
//        ThrowUtils.throwIf(maxNum > 10, ErrorCode.PARAMS_ERROR, "最多一次审核10张");
        ThrowUtils.throwIf(pictureAIReviewRequests.size() > 10, ErrorCode.PARAMS_ERROR, "最多一次审核10张");

        Set<Long> ids = pictureAIReviewRequests.stream().map(PictureAIReviewRequest::getId).collect(Collectors.toSet());
        List<Picture> pictures = this.listByIds(ids);
        for (Picture picture : pictures) {
            Long spaceId = picture.getSpaceId();
            // 虽然前端提供的是 审核公共图片页面 但是以防万一 再次进行校验一下有无空间id的图片
            if (spaceId != null) ThrowUtils.throwIf(true, ErrorCode.PARAMS_ERROR, "审核失败，仅对公共图片审核");
            String url = picture.getUrl();
            int startIndex = url.indexOf("public/");
            if (startIndex != -1) {
                url = url.substring(startIndex);
            }

            ImageAuditingResponse imageAuditingResponse = cosManager.reviewImage(url + " " + picture.getId());
            String taskId = imageAuditingResponse.getJobId(); // 假设 ImageAuditingResponse 包含 taskId
            taskQueue.add(taskId);
        }
        // ai审核完毕
        return true;

    }

    private void checkTaskStatus(String taskId) {
        int retryCount = 0;
        final int maxRetries = 5;
        final long retryInterval = 5000; // 5 seconds

        while (retryCount < maxRetries) {
            try {
                String[] split = taskId.split(" ");
                ImageAuditingResponse response = cosManager.selectReviewImage(split[0]);
                if (response.getState().equals("Success")) {
                    Long pictureId = null;
                    pictureId = Long.valueOf(split[1]);
                    handleAuditResult(split[0], response, pictureId);
                    return;
                }
            } catch (Exception e) {
                log.error("Error checking task status for taskId: {}", taskId, e);
            }

            retryCount++;
            try {
                TimeUnit.MILLISECONDS.sleep(retryInterval);
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
                log.error("Task status check thread interrupted", e);
                return;
            }
        }

        log.error("Max retries reached for taskId: {}", taskId);
    }

    private void handleAuditResult(String taskId, ImageAuditingResponse response, Long pictureId) {
        // 假设 response 包含审核结果
        boolean isPassed = response.getState().equals("Success");
        // 更新数据库中的图片审核状态
        Picture picture = new Picture();
        if (isPassed && pictureId != null) {
            String label = response.getLabel();
            if (label.equals(ReviewPictureConstant.NORMAL)) {
                picture.setReviewStatus(PictureReviewStatusEnum.PASS.getValue());
                picture.setReviewMessage("AI审核通过");
//                picture.setIsDelete(0);  是修改审核状态 麻痹 我改人家图片删除状态就够了 笑死了
//            审核人id为null的默认ai审核结果
            } else {
                picture.setReviewStatus(PictureReviewStatusEnum.REJECT.getValue());
                ReviewPictureEnum enumByValue = ReviewPictureEnum.getEnumByValue(label);
                picture.setReviewMessage("AI审核不通过，" + "原因：" + (enumByValue != null ? enumByValue.getText() : label));
            }
            picture.setReviewTime(new Date());
            picture.setId(pictureId);
            boolean result = this.updateById(picture);
            ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        } else {
            ThrowUtils.throwIf(true, ErrorCode.OPERATION_ERROR, "AI审核异常或图片id为空");
        }
    }


    @Override
    public void fillReviewParams(Picture picture, User loginUser) {
        if (userService.isAdmin(loginUser)) {
            // 管理员自动过审
            picture.setReviewStatus(PictureReviewStatusEnum.PASS.getValue());
            picture.setReviewerId(loginUser.getId());
            picture.setReviewMessage("管理员自动过审");
            picture.setReviewTime(new Date());
        } else {
            // 非管理员，创建或编辑都要改为待审核
            picture.setReviewStatus(PictureReviewStatusEnum.REVIEWING.getValue());
        }
    }

    @Override
    public Integer uploadPictureByBatch(PictureUploadByBatchRequest pictureUploadByBatchRequest, User loginUser) {
        String searchText = pictureUploadByBatchRequest.getSearchText();
        // 格式化数量
        Integer count = pictureUploadByBatchRequest.getCount();
        ThrowUtils.throwIf(count > 30, ErrorCode.PARAMS_ERROR, "最多 30 条");
//        给抓取图片后的名字自定义统一的前缀
        String namePrefix = pictureUploadByBatchRequest.getNamePrefix();
//        如果不存在 使用默认的搜索词searchText
        if (StrUtil.isBlank(namePrefix)) {
            namePrefix = searchText;
        }
        // 要抓取的地址
        String fetchUrl = String.format("https://cn.bing.com/images/async?q=%s&mmasync=1", searchText);
        Document document;
        try {
            document = Jsoup.connect(fetchUrl).get();
        } catch (IOException e) {
            log.error("获取页面失败", e);
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "获取页面失败");
        }
        Element div = document.getElementsByClass("dgControl").first();
        if (ObjUtil.isNull(div)) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "获取元素失败");
        }
        Elements imgElementList = div.select("img.mimg");
        int uploadCount = 0;
        for (Element imgElement : imgElementList) {
            String fileUrl = imgElement.attr("src");
            if (StrUtil.isBlank(fileUrl)) {
                log.info("当前链接为空，已跳过: {}", fileUrl);
                continue;
            }
            // 处理图片上传地址，防止出现转义问题
            int questionMarkIndex = fileUrl.indexOf("?");
            if (questionMarkIndex > -1) {
                fileUrl = fileUrl.substring(0, questionMarkIndex);
            }
            // 上传图片
            PictureUploadRequest pictureUploadRequest = new PictureUploadRequest();
            pictureUploadRequest.setPicName(namePrefix + uploadCount + 1);
            try {
                PictureVO pictureVO = this.uploadPicture(fileUrl, pictureUploadRequest, loginUser);
                log.info("图片上传成功, id = {}", pictureVO.getId());
                uploadCount++;
            } catch (Exception e) {
                log.error("图片上传失败", e);
                continue;
            }
            if (uploadCount >= count) {
                break;
            }
        }
        return uploadCount;
    }


    @Async
    @Override
    public void clearPictureFile(Picture oldPicture) {
        // 判断该图片是否被多条记录使用
        String pictureUrl = oldPicture.getUrl();
        long count = this.lambdaQuery()
                .eq(Picture::getUrl, pictureUrl)
                .count();
        // 有不止一条记录用到了该图片，不清理
        if (count > 1) {
            return;
        }
        //  注意，这里的 url 包含了域名，实际上只要传 key 值（存储路径）就够了
//        https://bsz2-1328061709.cos.ap-beijing.myqcloud.com/public/1897125115201302530/2025-03-09_RGW0EIN8FEE8ZgHd.webp
//        String fileName = pictureUrl.substring(pictureUrl.lastIndexOf('/') + 1);
        String fileName = extractPathFromUrl(pictureUrl);
        cosManager.deleteObject(fileName);
        // 清理缩略图
        String thumbnailUrl = extractPathFromUrl(oldPicture.getThumbnailUrl());
        // 优化 如果 缩略图也是webp的话 那么直接停止 因为前面已经删除了webp   !StrUtil.equals(thumbnailUrl, fileName)
        if (StrUtil.isNotBlank(thumbnailUrl) && !StrUtil.equals(thumbnailUrl, fileName)) {
            cosManager.deleteObject(thumbnailUrl);
        }
    }

    //    获取不包含域名的图片路径
    public static String extractPathFromUrl(String url) {
        // 找到第一个斜杠的位置，跳过协议和域名部分
        int startIndex = url.indexOf('/', url.indexOf("://") + 3);
        if (startIndex == -1) {
            return "";
        }
        return url.substring(startIndex);
    }

    @Override
    public void checkPictureAuth(User loginUser, Picture picture) {
        Long spaceId = picture.getSpaceId();
        if (spaceId == null) {
            // 公共图库，仅本人或管理员可操作
            if (!picture.getUserId().equals(loginUser.getId()) && !userService.isAdmin(loginUser)) {
                throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
            }
        } else {
            // 私有空间，仅空间管理员可操作
            if (!picture.getUserId().equals(loginUser.getId())) {
                throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
            }
        }
    }


    @Override
    public void deletePicture(long pictureId, User loginUser) {
        ThrowUtils.throwIf(pictureId <= 0, ErrorCode.PARAMS_ERROR);
        ThrowUtils.throwIf(loginUser == null, ErrorCode.NO_AUTH_ERROR);
        // 判断是否存在
        Picture oldPicture = this.getById(pictureId);
        ThrowUtils.throwIf(oldPicture == null, ErrorCode.NOT_FOUND_ERROR);
//        // 仅本人或管理员可删除
//        if (!oldPicture.getUserId().equals(loginUser.getId()) && !userService.isAdmin(loginUser)) {
//            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
//        }
//        现在有了删除图片的权限校验接口，所以上面的可以注释
//        像公共图库 只能本人或管理员才可以删除图片 ，私有空间仅创建图片的本人可以删除
        //已经改为使用注解鉴权
//        this.checkPictureAuth(loginUser, oldPicture);
        /**
         * 删除的图片是否为私有空间的图片  看spaceId
         *  是： 更新space表里 size - 当前图片大小； total - 1
         */

        // 开启事务
        transactionTemplate.execute(status -> {
            // 操作数据库
            boolean result = this.removeById(pictureId);
            ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
            // 释放额度
            Long spaceId = oldPicture.getSpaceId();
            if (spaceId != null) {
                boolean update = spaceService.lambdaUpdate()
                        .eq(Space::getId, spaceId)
                        .setSql("totalSize = totalSize - " + oldPicture.getPicSize())
                        .setSql("totalCount = totalCount - 1")
                        .update();
                ThrowUtils.throwIf(!update, ErrorCode.OPERATION_ERROR, "额度更新失败");
            }
            return true;
        });
        //清理图片资源
        this.clearPictureFile(oldPicture);
    }


    @Override
    public void editPicture(PictureEditRequest pictureEditRequest, User loginUser) {
        // 判断是否存在
        long id = pictureEditRequest.getId();
        Picture oldPicture = this.getById(id);
        ThrowUtils.throwIf(oldPicture == null, ErrorCode.NOT_FOUND_ERROR);
        // 只有spaceId为null的公共图片 才去校验文本是否合规
        Long spaceId = oldPicture.getSpaceId();
        if (spaceId == null) {
            // 审核文本是否合规
            String name = pictureEditRequest.getName();
            String introduction = pictureEditRequest.getIntroduction();
            TextAuditingResponse textAuditingResponse = cosManager.reviewText(name + " " + introduction);
            String state = textAuditingResponse.getJobsDetail().getState();
            if (state.equals("Success")) {
                String label = textAuditingResponse.getJobsDetail().getLabel();
                if (!ReviewPictureEnum.NORMAL.getValue().equals(label))
                    ThrowUtils.throwIf(true, ErrorCode.PARAMS_ERROR, "文本违规-" + label);
            }
        }

        // 在此处将实体类和 DTO 进行转换
        Picture picture = new Picture();
        BeanUtils.copyProperties(pictureEditRequest, picture);
        // 注意将 list 转为 string
        picture.setTags(JSONUtil.toJsonStr(pictureEditRequest.getTags()));
        // 设置编辑时间
        picture.setEditTime(new Date());
        // 数据校验
        this.validPicture(picture);
//        // 判断是否存在  移到上面了 由于要校验文本合规性使用
//        long id = pictureEditRequest.getId();
//        Picture oldPicture = this.getById(id);
//        ThrowUtils.throwIf(oldPicture == null, ErrorCode.NOT_FOUND_ERROR);
        // 校验权限
        //已经改为使用注解鉴权
//        checkPictureAuth(loginUser, oldPicture);
        // 补充审核参数
        this.fillReviewParams(picture, loginUser);
        // 操作数据库
        boolean result = this.updateById(picture);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
    }


    @Override
    public List<PictureVO> searchPictureByColor(Long spaceId, String picColor, User loginUser) {
        // 1. 校验参数
        ThrowUtils.throwIf(spaceId == null || StrUtil.isBlank(picColor), ErrorCode.PARAMS_ERROR);
        ThrowUtils.throwIf(loginUser == null, ErrorCode.NO_AUTH_ERROR);
        // 2. 校验空间权限
        Space space = spaceService.getById(spaceId);
        ThrowUtils.throwIf(space == null, ErrorCode.NOT_FOUND_ERROR, "空间不存在");
        // 已经改为使用注解鉴权  并且团队空间成员是可以访问空间的才对 比如使用颜色搜图功能
//        if (!loginUser.getId().equals(space.getUserId())) {
//            throw new BusinessException(ErrorCode.NO_AUTH_ERROR, "没有空间访问权限");
//        }
        // 3. 查询该空间下所有图片（必须有主色调）
        List<Picture> pictureList = this.lambdaQuery()
                .eq(Picture::getSpaceId, spaceId)
                .isNotNull(Picture::getPicColor)
                .list();
        // 如果没有图片，直接返回空列表
        if (CollUtil.isEmpty(pictureList)) {
            return Collections.emptyList();
        }
        // 将目标颜色转为 Color 对象
        Color targetColor = Color.decode(picColor);
        // 4. 计算相似度并排序
        List<Picture> sortedPictures = pictureList.stream()
                .sorted(Comparator.comparingDouble(picture -> {
                    // 提取图片主色调
                    String hexColor = picture.getPicColor();
                    // 没有主色调的图片放到最后  避免空字符串的情况
                    if (StrUtil.isBlank(hexColor)) {
                        return Double.MAX_VALUE;
                    }
                    Color pictureColor = Color.decode(hexColor);
                    // 越大越相似  但是这里sorted是升序 所以加负号  越小越靠前
                    return -ColorSimilarUtils.calculateSimilarity(targetColor, pictureColor);
                }))
                // 取前 12 个
                .limit(12)
                .collect(Collectors.toList());

        // 转换为 PictureVO
        return sortedPictures.stream()
                .map(PictureVO::objToVo)
                .collect(Collectors.toList());
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void editPictureByBatch(PictureEditByBatchRequest pictureEditByBatchRequest, User loginUser) {
        List<Long> pictureIdList = pictureEditByBatchRequest.getPictureIdList();
        Long spaceId = pictureEditByBatchRequest.getSpaceId();
        String category = pictureEditByBatchRequest.getCategory();
        List<String> tags = pictureEditByBatchRequest.getTags();

        // 1. 校验参数
        ThrowUtils.throwIf(spaceId == null || CollUtil.isEmpty(pictureIdList), ErrorCode.PARAMS_ERROR);
        ThrowUtils.throwIf(loginUser == null, ErrorCode.NO_AUTH_ERROR);
        // 2. 校验空间权限
        Space space = spaceService.getById(spaceId);
        ThrowUtils.throwIf(space == null, ErrorCode.NOT_FOUND_ERROR, "空间不存在");
        if (!loginUser.getId().equals(space.getUserId())) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR, "没有空间访问权限");
        }

        // 3. 查询指定图片，仅选择需要的字段
        /**
         * 为什么还要再查一遍 前端不是传过id列表了吗？
         * 因为要确保表里面有对应的id  才会修改这些实际存在的id的图片信息
         */
        List<Picture> pictureList = this.lambdaQuery()
                .select(Picture::getId, Picture::getSpaceId)
                .eq(Picture::getSpaceId, spaceId)
                .in(Picture::getId, pictureIdList)
                .list();

        if (pictureList.isEmpty()) {
            return;
        }
        // 4. 更新分类和标签
        pictureList.forEach(picture -> {
            if (StrUtil.isNotBlank(category)) {
                picture.setCategory(category);
            }
            if (CollUtil.isNotEmpty(tags)) {
                picture.setTags(JSONUtil.toJsonStr(tags));
            }
        });


        // 批量重命名
        String nameRule = pictureEditByBatchRequest.getNameRule();
        fillPictureWithNameRule(pictureList, nameRule);


        // 5. 批量更新
        boolean result = this.updateBatchById(pictureList);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
    }

    @Override
    public CreateOutPaintingTaskResponse createPictureOutPaintingTask(CreatePictureOutPaintingTaskRequest createPictureOutPaintingTaskRequest, User loginUser) {
        // 获取图片信息
        Long pictureId = createPictureOutPaintingTaskRequest.getPictureId();
        Picture picture = Optional.ofNullable(this.getById(pictureId))  //如果pictureId为null，就会执行后边的orElseThrow
                .orElseThrow(() -> new BusinessException(ErrorCode.NOT_FOUND_ERROR));
        // 权限校验
        //已经改为使用注解鉴权
//        checkPictureAuth(loginUser, picture);
        // 构造请求参数
        CreateOutPaintingTaskRequest taskRequest = new CreateOutPaintingTaskRequest();
        CreateOutPaintingTaskRequest.Input input = new CreateOutPaintingTaskRequest.Input();
        input.setImageUrl(picture.getUrl());
        taskRequest.setInput(input);
        BeanUtil.copyProperties(createPictureOutPaintingTaskRequest, taskRequest);
        // 创建任务
        return aliYunAiApi.createOutPaintingTask(taskRequest);
    }

    @Override
    public CreateText2ImageResponse createPictureText2ImageTask(CreatePictureText2ImageTaskRequest createPictureText2ImageTaskRequest) {
        // 获取图片信息
        Long pictureId = createPictureText2ImageTaskRequest.getPictureId();
        Picture picture = Optional.ofNullable(this.getById(pictureId))  //如果pictureId为null，就会执行后边的orElseThrow
                .orElseThrow(() -> new BusinessException(ErrorCode.NOT_FOUND_ERROR));
        // 权限校验
        //已经改为使用注解鉴权
//        checkPictureAuth(loginUser, picture);
        // 构造请求参数
//        CreateOutPaintingTaskRequest taskRequest = new CreateOutPaintingTaskRequest();
        CreateText2ImageRequest taskRequest = new CreateText2ImageRequest();
//        CreateOutPaintingTaskRequest.Input input = new CreateOutPaintingTaskRequest.Input();
        CreateText2ImageRequest.Input input = new CreateText2ImageRequest.Input();
//        input.setImageUrl(picture.getUrl());
        input.setImageUrl("https://www.codefather.cn/logo.png");
        taskRequest.setInput(input);
        BeanUtil.copyProperties(createPictureText2ImageTaskRequest, taskRequest);
        // 创建任务
        return aliYunAiApi.createTextToImageTask(taskRequest);
    }


    @Override
    public void likePicture(Long pictureId, User loginUser) {
        /**
         * 增加校验
         * 只允许对公共图库的图片进行点赞 否则会影响后续推荐的代码 （这里做了过滤 那么就不用改动推荐代码了）
         */
        Picture picture = this.getById(pictureId);
        Long spaceId = picture.getSpaceId();
        ThrowUtils.throwIf(spaceId != null, ErrorCode.PARAMS_ERROR, "不允许点赞非公共图库的图片");
        // 1.获取登录用户
        Long userId = loginUser.getId();
        // 2.判断当前登录用户是否已经点赞
        String key = PICTURE_LIKED_KEY + pictureId;
//        Boolean isMember = stringRedisTemplate.opsForSet().isMember(key, userId.toString());
        Double score = stringRedisTemplate.opsForZSet().score(key, userId.toString());
        if (score == null) {
            //3.如果未点赞，可以点赞
            //3.1 数据库点赞数+1
            boolean isSuccess = update().setSql("liked = liked + 1").eq("id", pictureId).update();
            //3.2 保存用户到Redis的set集合
            if (isSuccess) {
                stringRedisTemplate.opsForZSet().add(key, userId.toString(), System.currentTimeMillis());
            }
        } else {
            //4.如果已点赞，取消点赞
            //4.1 数据库点赞数-1
            boolean isSuccess = update().setSql("liked = liked - 1").eq("id", pictureId).update();
            //4.2 把用户从Redis的set集合移除
            if (isSuccess) {
                stringRedisTemplate.opsForZSet().remove(key, userId.toString());
            }
        }
    }


    public void isPictureLiked(Picture picture, User loginUser) {
        // 1.获取登录用户
        if (loginUser == null) {
            // 用户未登录，无需查询是否点赞
            return;
        }
        Long userId = loginUser.getId();
        // 2.判断当前登录用户是否已经点赞
        String key = "picture:liked:" + picture.getId();
        Double score = stringRedisTemplate.opsForZSet().score(key, userId.toString());
        picture.setIsLike(score != null);
    }

    @Override
    public PictureVO getPictureVOById(long id, HttpServletRequest request) {
        // 查询数据库
        Picture picture = this.getById(id);
        ThrowUtils.throwIf(picture == null, ErrorCode.NOT_FOUND_ERROR);
        /**
         * 优化 就是 如果图片的审核状态为待审核 或者是 拒绝的情况 就不能给前端返回 图片信息
         */
//        if (picture.getReviewStatus() == PictureReviewStatusEnum.REVIEWING.getValue() ||
//                picture.getReviewStatus() == PictureReviewStatusEnum.REJECT.getValue()) {
//            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
//        }
        // 空间的图片，需要校验权限
        Space space = null;
//        对于普通用户 是不能去查其他用户私有空间里的图片的
        Long spaceId = picture.getSpaceId();
        if (spaceId != null) {
            //编程试校验权限  因为 这里传来pictureId  导致sa-token必须校验用户登录
            //可是公共图库哪里是可以让用户看详情的  应该是这样
            boolean hasPermission = StpKit.SPACE.hasPermission(SpaceUserPermissionConstant.PICTURE_VIEW);
            ThrowUtils.throwIf(!hasPermission, ErrorCode.NO_AUTH_ERROR);
            //已经改为使用注解鉴权
//            pictureService.checkPictureAuth(userService.getLoginUser(request), picture);
            space = spaceService.getById(spaceId);
            ThrowUtils.throwIf(space == null, ErrorCode.NOT_FOUND_ERROR, "空间不存在");
        }
//        要给前端返回一个当前用户请求对应的权限列表，前端就能知道该不该提供如编辑按钮的展示
        // 获取权限列表
//        User loginUser = userService.getLoginUser(request);


        /**
         * 用户分享图片 其他未登录用户可以直接扫码查看图片 不用登录  下面这个监测到未登录 直接就返回null了 不会抛出未登录异常
         */
        User loginUser = userService.getLoginUserShared(request);
        List<String> permissionList = spaceUserAuthManager.getPermissionList(space, loginUser, picture.getUserId());
        System.out.println(permissionList);
        PictureVO pictureVO = this.getPictureVO(picture, request);
        pictureVO.setPermissionList(permissionList);
        // 往redis和数据库里存储更新浏览记录
        if (loginUser != null) {
            recordView(loginUser.getId(), picture.getId());
        } else {
            // 记录匿名用户浏览（可选）
            stringRedisTemplate.opsForZSet().add("guest:viewed:pictures", picture.getId().toString(), System.currentTimeMillis());
        }
        return pictureVO;
    }

    @Resource
    private ImageUnderstandingFacade imageUnderstandingFacade;

    @Async
    @Override
    public void savePictureElements(String url, String description, Long id) {
        // 参数校验（非空检查属于业务校验，直接抛业务异常）
        if (StrUtil.isBlank(url) || StrUtil.isBlank(description)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "参数不能为空");
        }

        try {
            // 1. 调用百度AI识别图片
            String content = imageUnderstandingFacade.analyzeImageAndGetDescription(url, description);

            // 2. 调用DeepSeek解析元素
            List<String> keywords = deepseekApi.parseImageSearchKeywords(content); // 注意这里应该是content而非description

            // 3. 保存到数据库等后续操作
            Picture picture = new Picture();
            picture.setId(id);
            picture.setElements(JSONUtil.toJsonStr(keywords));
            // 注意 前面已经进行了picture表的插入 这里是更新才对 不然继续插入 会报错的 我这里是报了url不能为空才反应过来
            int result = pictureMapper.updateById(picture);
            ThrowUtils.throwIf(result <= 0, ErrorCode.OPERATION_ERROR, "保存图片元素失败");
        } catch (IOException e) {
            // 记录原始异常（重要！方便排查问题）
            log.error("图片元素解析失败，url: {}, 原因: {}", url, e.getMessage(), e);
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "图片解析服务暂时不可用");
        } catch (Exception e) {
            // 兜底异常处理
            log.error("保存图片元素未知错误，url: {}", url, e);
            throw new BusinessException(ErrorCode.SYSTEM_ERROR);
        }
    }

    private void recordView(Long userId, Long pictureId) {
        // 1. Redis记录（实时推荐使用）
        String userViewKey = "user:view:" + userId;
        String pictureViewKey = "picture:viewed:" + pictureId;

        long now = System.currentTimeMillis();
        stringRedisTemplate.opsForZSet().add(userViewKey, pictureId.toString(), now);
        stringRedisTemplate.opsForZSet().add(pictureViewKey, userId.toString(), now);

        // 2. 更新全局计数
        stringRedisTemplate.opsForHash().increment("picture:view_counts",
                pictureId.toString(), 1);

        // 3. 异步落库（可选）
        this.saveViewLog(userId, pictureId);
    }


    @Async
    public void saveViewLog(Long userId, Long pictureId) {
        // 1. 写入MySQL浏览记录表
        userPictureViewMapper.upsertViewRecord(userId, pictureId);


        // 2. 更新picture表的view_count
        /**
         * 用户点击进入图片详情后 这边看不到浏览量 所以可以先查picture 后修改浏览量 用户返回首页时 这时可以看到浏览量的修改
         * 如果详情页可以看到浏览量的话 那就得先查picture 进行校验，之后再更新，最后再查一遍picture
         */
        this.lambdaUpdate()
                .setSql("viewCount = viewCount + 1")
                .eq(Picture::getId, pictureId)
                .update();

    }

    /**
     * nameRule 格式：图片{序号}
     *
     * @param pictureList
     * @param nameRule
     */
    private void fillPictureWithNameRule(List<Picture> pictureList, String nameRule) {
        if (CollUtil.isEmpty(pictureList) || StrUtil.isBlank(nameRule)) {
            return;
        }
        long count = 1;
        try {
            for (Picture picture : pictureList) {
                String pictureName = nameRule.replaceAll("\\{序号}", String.valueOf(count++));
                picture.setName(pictureName);
            }
        } catch (Exception e) {
            log.error("名称解析错误", e);
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "名称解析错误");
        }
    }


}




